<?php

declare (strict_types=1);
/**
 * @copyright 深圳市易果网络科技有限公司
 * @version 1.0.0
 * @link https://dayiguo.com
 */

namespace App\Service\User;

use App\Dao\CouponPaymentDao;

use App\Exception\CustomException;
use App\Service\Service;

use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Snowflake\IdGeneratorInterface;

/**
 * 优惠券支付服务
 *
 * @author 张昊(2396675557@qq.com)
 * @package App\Service\User
 */
class CouponPaymentService extends Service
{
    /**
     * 支付记录 DAO
     *
     * @Inject()
     * @var CouponPaymentDao
     */
    private $dao;

    /**
     * 发起在线支付
     *
     * @author 张昊(2396675557@qq.com)
     * @param array $data
     * @param string $channel
     * @param string $subject
     * @return mixed
     */
    public function buildPay(array $data, string $channel, string $subject)
    {
        Db::beginTransaction();
        try {
            $pay_no = (string)$this->container->get(IdGeneratorInterface::class)->generate();
            $this->dao->firstOrCreate($data, [
                'pay_no' => $pay_no,
                'channel' => $channel
            ]);

            switch ($channel) {
                case 'alipay': // 支付宝

                    $result = (new \App\Kernel\Payment\Alipay)->app_pay($pay_no, $data['amount'], $subject);
                    $result = http_build_query($result);
                    break;

                case 'wechat': // 微信
                    throw new CustomException('PAYMENT.WECHAT_PAY_NOT_ENABLE');
                    break;

                default:
                    throw new CustomException('PAY.DOES_NOT_PAYMENT_METHOD');
            }

            Db::commit();
            return ['pay_no' => $pay_no, 'result' => $result];
        }
        catch (CustomException $e) {
            Db::rollBack();
            $this->error($e->getMessage());
            return false;
        }
    }

    /**
     * 支付宝回调
     *
     * @param array $params
     */
    public function aliNotify(array $params)
    {
        // todo
    }
}